package controllers

import (
	"github.com/gin-gonic/gin"
	"goblog/auth"
	"github.com/dgrijalva/jwt-go"
	"net/http"
	"goblog/models"
	"fmt"
)


//登录 生成token
func GetToken(c *gin.Context)  {
	j := &auth.JWT{
		[]byte("goblog"),
	}

	var u models.User
	if c.ShouldBind(&u) != nil{
		c.JSON(http.StatusOK,models.ResE("参数错误"))
		return
	}

	//获取用户名密码
	user, err := models.GetUserByNameAndPwd(u.Name,u.Password)
	if err != nil {
		c.JSON(http.StatusOK,models.ResE("获取用户信息失败"))
		return
	}

	claims := auth.CustomClaims{
		user.Id,
		user.Name,
		user.Email,
		jwt.StandardClaims{
			ExpiresAt: 15000, //time.Now().Add(24 * time.Hour).Unix()
			Issuer: user.Name,
		},
	}
	token, err := j.CreateToken(claims)
	if err != nil {
		c.JSON(http.StatusOK, models.ResE(err.Error()))
		c.Abort()
	}
	//c.String(http.StatusOK, token+"---------------<br>")
	res, err := j.ParseToken(token)
	if err != nil {
		//过期
		if err == auth.TokenExpired {
			newToken, err := j.RefreshToken(token)
			if err != nil {
				c.JSON(http.StatusOK, models.ResE(err.Error()))
			} else {
				c.JSON(http.StatusOK, models.ResS(newToken))
			}
		} else {
			c.JSON(http.StatusOK, models.ResE(err.Error()))
		}
	} else {
		//校验成功的信息
		//c.JSON(http.StatusOK, res)
		fmt.Println(res)
		c.JSON(http.StatusOK,models.ResS(token))
	}
}